package networkcontroller.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * class which handles xml data in packets
 * 
 * @author maciek
 * 
 */
public abstract class XML
{
	/**
	 * document created from data
	 */
	protected Document			document	= null;
	/**
	 * document builder object
	 */
	protected DocumentBuilder	builder;

	/**
	 * constructor which creates xml object from data in packet
	 * 
	 * @param XMLData
	 *            byte array of data
	 */
	protected XML(byte[] XMLData)
	{
		createDocumentBuilderFactory();
		ByteArrayInputStream bais = new ByteArrayInputStream(XMLData);
		System.out.println(new String(XMLData));
		try
		{
			document = builder.parse(bais);
		} catch (SAXException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * constructor which creates only document factory
	 */
	public XML()
	{
		createDocumentBuilderFactory();
	}

	/**
	 * creates document factory
	 */
	private void createDocumentBuilderFactory()
	{
		try
		{
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * creates new document
	 */
	protected void createNewDocument()
	{
		document = builder.newDocument();
	}

	/**
	 * gets data of xml
	 * 
	 * @return byte array of data
	 */
	public byte[] getXMLByteData()
	{
		try
		{
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			StreamResult result = new StreamResult(baos);
			DOMSource source = new DOMSource(document);
			transformer.transform(source, result);
			return baos.toByteArray();
		} catch (TransformerConfigurationException e)
		{
			e.printStackTrace();
		} catch (TransformerException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
